<template>
  <div class="registration-order-page">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>挂号订单管理</h1>
    </div>

    <!-- 筛选区域 -->
    <el-card class="filter-card" shadow="never">
      <template #header>
        <div class="card-header">
          <el-icon><Grid /></el-icon>
          <span>筛选</span>
        </div>
      </template>
      <el-form :model="filterForm" inline>
        <el-form-item>
          <el-input
            v-model="filterForm.keyword"
            placeholder="输入订单号或用户名"
            clearable
            style="width: 250px"
          />
        </el-form-item>
        <el-form-item label="日期">
          <el-date-picker
            v-model="filterForm.startTime"
            type="datetime"
            placeholder="开始时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 180px"
          />
          <span style="margin: 0 8px">至</span>
          <el-date-picker
            v-model="filterForm.endTime"
            type="datetime"
            placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 180px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleFilter">
            <el-icon><Search /></el-icon>
            筛选
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据列表 -->
    <el-card class="data-card" shadow="never">
      <template #header>
        <div class="card-header">
          <el-icon><List /></el-icon>
          <span>数据列表</span>
        </div>
      </template>

      <!-- 状态标签 -->
      <el-tabs v-model="activeStatus" @tab-click="handleStatusChange">
        <el-tab-pane label="全部" name="all" />
        <el-tab-pane label="待支付" name="0" />
        <el-tab-pane label="已完成" name="5" />
        <el-tab-pane label="已取消" name="10" />
        <el-tab-pane label="已退款" name="15" />
      </el-tabs>

      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="orderNo" label="订单编号" width="180" />
        <el-table-column prop="createTime" label="提交时间" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="patientName" label="用户名" width="120" />
        <el-table-column prop="doctorName" label="医生" width="120" />
        <el-table-column prop="departmentName" label="科室" width="120" />
        <el-table-column prop="amount" label="挂号费" width="120">
          <template #default="scope">
            ¥{{ scope.row.amount?.toFixed(2) || "0.00" }}
          </template>
        </el-table-column>
        <el-table-column prop="orderStatus" label="订单状态" width="120">
          <template #default="scope">
            <el-tag :type="getOrderStatusType(scope.row.orderStatus)">
              {{
                scope.row.orderStatusName ||
                getOrderStatusText(scope.row.orderStatus)
              }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="handleView(scope.row)"
            >
              查看
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, nextTick } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { Grid, List, Search } from "@element-plus/icons-vue";
import { OrderAPI } from "../api/order";

// 路由
const router = useRouter();

// 订单状态枚举
enum OrderStatus {
  PENDING = 0, // 待支付
  COMPLETED = 5, // 已完成
  CANCELLED = 10, // 已取消
  REFUNDED = 15, // 已退款
}

// 响应式数据
const loading = ref(false);
const activeStatus = ref("all");
const selectedRows = ref<any[]>([]);
const tableData = ref([]);

// 筛选表单
const filterForm = reactive({
  keyword: "",
  startTime: "",
  endTime: "",
});

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
});

// 计算当前订单状态
const currentOrderStatus = computed(() => {
  if (activeStatus.value === "all") return undefined;
  return Number(activeStatus.value);
});

// 获取状态类型
const getOrderStatusType = (status: number) => {
  switch (status) {
    case OrderStatus.PENDING:
      return "warning";
    case OrderStatus.COMPLETED:
      return "success";
    case OrderStatus.CANCELLED:
      return "info";
    case OrderStatus.REFUNDED:
      return "danger";
    default:
      return "";
  }
};

// 获取状态文本
const getOrderStatusText = (status: number) => {
  switch (status) {
    case OrderStatus.PENDING:
      return "待支付";
    case OrderStatus.COMPLETED:
      return "已完成";
    case OrderStatus.CANCELLED:
      return "已取消";
    case OrderStatus.REFUNDED:
      return "已退款";
    default:
      return "未知";
  }
};

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return "";
  return new Date(dateTime).toLocaleString("zh-CN");
};

// 加载挂号订单数据
const loadRegistrationOrders = async () => {
  try {
    loading.value = true;
    const params = {
      PageIndex: pagination.currentPage,
      PageSize: pagination.pageSize,
      Keyword: filterForm.keyword,
      StartTime: filterForm.startTime,
      EndTime: filterForm.endTime,
      OrderStatus: currentOrderStatus.value,
    };

    console.log("加载挂号订单参数:", params);
    const response = await OrderAPI.getRegistrationOrdersPage(params);
    console.log("挂号订单响应:", response);

    tableData.value = response.data?.data || [];
    pagination.total = response.data?.totalCount || 0;
  } catch (error) {
    console.error("加载挂号订单失败:", error);
    ElMessage.error("加载挂号订单失败");
  } finally {
    loading.value = false;
  }
};

// 筛选
const handleFilter = () => {
  pagination.currentPage = 1;
  loadRegistrationOrders();
};

// 状态切换
const handleStatusChange = (tab: any) => {
  console.log("状态切换:", tab.props.name);

  // 直接计算订单状态，避免响应式延迟
  const orderStatus =
    tab.props.name === "all" ? undefined : Number(tab.props.name);

  // 使用 nextTick 确保 DOM 更新后再调用 API
  nextTick(() => {
    const tempLoadRegistrationOrders = async () => {
      try {
        loading.value = true;
        const params = {
          PageIndex: pagination.currentPage,
          PageSize: pagination.pageSize,
          Keyword: filterForm.keyword,
          StartTime: filterForm.startTime,
          EndTime: filterForm.endTime,
          OrderStatus: orderStatus,
        };

        console.log("状态切换参数:", params);
        const response = await OrderAPI.getRegistrationOrdersPage(params);
        console.log("状态切换响应:", response);

        tableData.value = response.data?.data || [];
        pagination.total = response.data?.totalCount || 0;
      } catch (error) {
        console.error("状态切换失败:", error);
        ElMessage.error("状态切换失败");
      } finally {
        loading.value = false;
      }
    };

    tempLoadRegistrationOrders();
  });
};

// 表格选择
const handleSelectionChange = (rows: any[]) => {
  selectedRows.value = rows;
};

// 查看详情
const handleView = (row: any) => {
  router.push(`/orders/registration-detail/${row.id}`);
};

// 分页大小改变
const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  loadRegistrationOrders();
};

// 当前页改变
const handleCurrentChange = (page: number) => {
  pagination.currentPage = page;
  loadRegistrationOrders();
};

// 组件挂载
onMounted(() => {
  loadRegistrationOrders();
});
</script>

<style scoped>
.registration-order-page {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.filter-card {
  margin-bottom: 20px;
}

.data-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  font-weight: 600;
  color: #303133;
}

.card-header .el-icon {
  margin-right: 8px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

:deep(.el-tabs__header) {
  margin-bottom: 20px;
}

:deep(.el-table) {
  margin-bottom: 20px;
}

:deep(.el-form-item) {
  margin-bottom: 16px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

@media (max-width: 768px) {
  .registration-order-page {
    padding: 10px;
  }

  .page-header h1 {
    font-size: 20px;
  }

  :deep(.el-form--inline .el-form-item) {
    display: block;
    margin-right: 0;
  }
}
</style>